package com.example.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pt.entity.TorrentInfoHash;
import com.example.pt.mapper.TorrentInfoHashMapper;
import com.example.pt.service.TorrentInfoHashService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 种子ID与InfoHash映射Service实现类
 */
@Service
public class TorrentInfoHashServiceImpl extends ServiceImpl<TorrentInfoHashMapper, TorrentInfoHash> implements TorrentInfoHashService {

    @Override
    public TorrentInfoHash saveMapping(Integer tid, String infoHash) {
        // 查询是否已存在映射关系
        LambdaQueryWrapper<TorrentInfoHash> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TorrentInfoHash::getTid, tid);
        
        TorrentInfoHash mapping = this.getOne(queryWrapper);
        
        if (mapping == null) {
            // 不存在则创建新的映射关系
            mapping = new TorrentInfoHash();
            mapping.setTid(tid);
            mapping.setInfoHash(infoHash);
            mapping.setCreateTime(new Date());
            this.save(mapping);
        } else if (!infoHash.equals(mapping.getInfoHash())) {
            // 存在但InfoHash不同，则更新InfoHash
            mapping.setInfoHash(infoHash);
            this.updateById(mapping);
        }
        
        return mapping;
    }

    @Override
    public String getInfoHashByTid(Integer tid) {
        LambdaQueryWrapper<TorrentInfoHash> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TorrentInfoHash::getTid, tid);
        queryWrapper.select(TorrentInfoHash::getInfoHash);
        
        TorrentInfoHash mapping = this.getOne(queryWrapper);
        
        return mapping != null ? mapping.getInfoHash() : null;
    }

    @Override
    public Integer getTidByInfoHash(String infoHash) {
        LambdaQueryWrapper<TorrentInfoHash> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TorrentInfoHash::getInfoHash, infoHash);
        queryWrapper.select(TorrentInfoHash::getTid);
        
        TorrentInfoHash mapping = this.getOne(queryWrapper);
        
        return mapping != null ? mapping.getTid() : null;
    }
} 